<template>
  <div>
    <cusDialog :title="roleForm.id ? '修改角色' : '添加角色'" ref="dialog" width="600px" headCss="float:left;"
      @confrim="confrimHandler" @hideHandler="hideHandler">
      <el-form :model="roleForm" ref="roleFormRef" :inline="true" :rules="rules" label-width="90">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" maxlength="30" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.descr" maxlength="30" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <p class="tit">权限列表</p>
      <cusCard color="#F3F3F4" padding="16px 0 16px 16px">
        <div class="treeBox">
          <roleTree ref="roleTreeRef" :resourceIdList="resourceIdList"></roleTree>
        </div>
      </cusCard>
    </cusDialog>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import roleTree from "./roleTree.vue";
import { reqRoleInfo, reqAddRole, reqModifyRole, reqRoleSource, reqResourceRoleRelation, } from "@/api/business/role";
import type { FormInstance, FormRules } from "element-plus";
import { useUserStoreHook } from "@/store/modules/user";
const router = useRouter();
const userStore = useUserStoreHook();
const formOrigin = () => ({
  name: "",
  descr: "",
  id: "",
});

const roleForm = ref(formOrigin());
const emits = defineEmits<{
  (event: "onInit"): void;
}>();

const dialog = ref();
const rules = reactive<FormRules>({
  name: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
});

const show = (id) => {
  if (id) {
    roleForm.value.id = id;
    getRoleSource();
    getRoleInfo();
  }
  dialog.value.show = true;
};
const resourceIdList = ref([]);
// 请求角色按钮信息
const getRoleSource = () => {
  reqRoleSource({ roleId: roleForm.value.id }).then((res) => {
    if (res.code == 1) {
      resourceIdList.value = res.data;
      nextTick(() => {
        roleTreeRef.value.getTreeData();
      });
      console.log('tttt', resourceIdList.value);
    }
  });
};
// 查询角色信息
const getRoleInfo = () => {
  reqRoleInfo({ id: roleForm.value.id }).then((res) => {
    if (res.code == 1) {
      roleForm.value = res.data;
    }
  });
};

// 添加角色
const getAddRole = () => {
  delete roleForm.value.id;
  reqAddRole({ ...roleForm.value }).then((res) => {
    if (res.code == 1) {
      roleForm.value.id = res.data;
      saveRoleResource().then(() => {
        dialog.value.show = false;
        ElMessage.success("创建角色成功");
        emits("onInit");
      });
      // emits("onInit");
    } else {
      ElMessage.info(res.msg);
    }
  });
};

// 修改角色
const getModifyRole = () => {
  reqModifyRole({ ...roleForm.value }).then((res) => {
    if (res.code == 1) {
      saveRoleResource().then(() => {
        ElMessage.success("修改角色信息成功");
        dialog.value.show = false;
        emits("onInit");
        if (userStore.pinia_userInfo.roleInfo.some((el) => el.id == roleForm.value.id)) {
          ElMessageBox.confirm(
            "您修改了当前用户角色,需要刷新页面才可生效,是否立即刷新?"
          )
            .then(() => {
              window.location.reload();
            })
            .catch(() => {
              // catch error
            });
        }
      });
      // emits("onInit");
    } else {
      ElMessage.info(res.msg);
    }
  });
};

// 保存角色资源关系
const saveRoleResource = () => {
  let resourceIdList = roleTreeRef.value.getCheckedNodes();
  // console.log('传递的参数', resourceIdList);
  return new Promise<void>((resolve, reject) => {
    reqResourceRoleRelation({
      roleId: roleForm.value.id,
      resourceIdList: JSON.stringify(resourceIdList),
    }).then((res) => {
      if (res.code == 1) resolve();
      else ElMessage.info(res.msg);
    });
  });
};

const roleFormRef = ref();

const confrimHandler = () => {
  roleFormRef.value.validate((valid) => {
    if (valid) {
      if (roleForm.value.id) {
        getModifyRole();
      } else {
        getAddRole();
      }
    }
  });
};
const roleTreeRef = ref();
// 初始化
const hideHandler = () => {
  roleForm.value = formOrigin();
  roleTreeRef.value.clearTree();
  roleFormRef.value.resetFields();
};

defineExpose({ show });
</script>

<style lang="scss" scoped>
.tit {
  font-size: 16px;
  margin-bottom: 10px;
}

.treeBox {
  max-height: 400px;
  overflow-y: scroll;
}
</style>